package cn.itcast.web.task;

import cn.itcast.domain.system.User;
import cn.itcast.service.system.UserService;
import cn.itcast.utils.SmsUtils;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.rabbit.SmsProducer;
import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SmsTask{
    //定时任务 发生生日祝福
//用户表中具有用户出生年月(1990-07-08)和电话号码的字段，在当天10点发送短信祝福
    @Autowired
    private UserService userService;
    @Autowired
    private SmsProducer smsProducer;

    public void executeSms() throws ClientException {
        System.out.println("定时器内的方法触发咯");
        //获取到user list
        List<User> user = userService.findUser();
        //循环遍历 判断该用户的生日和手机号是否为null
        for (User u : user) {
            if (!u.getBirthday().isEmpty()&&!u.getTelephone().isEmpty()){
                String birthday = u.getBirthday();
                String[] bd = birthday.split("-");

                String today = SimpleDateFormat.getDateInstance().format(new Date());
                String[] td = today.split("-");

                if (bd[1].equals(td[1])&&bd[2].equals(td[2])){
                    String signName="黑马小天才";
                    String phoneNumbers=u.getTelephone();
                    String templateCode="SMS_201650268";
                    //code的随机数
                    String number = RandomStringUtils.randomNumeric(6);
                    String param="{ \"code\":\""+number+"\"}";


                    Map<String,String> map = new HashMap<>();
                    map.put("signName",signName); //签名
                    map.put("phoneNumbers",phoneNumbers);  //手机号
                    map.put("templateCode",templateCode); //模板
                    map.put("param",param);//验证码
                    smsProducer.send("sms",map);
                }

            }
        }


    }
}
